package imwallet.dichen.com.library.framework;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import java.util.List;

import imwallet.dichen.com.library.R;

/**
 * 中转activity
 *
 * @author Administrator
 * @date 2018/7/2
 */

public class RouterActivity extends BaseActivity {
    private String mTag;
    private OnBackListener mOnBackListener;
    private FragmentManager mFragmentManager;
    public static String KEY_TARGET = "key_target";
    public static String KEY_TYPE = "key_type";
    public static String KEY_DATA = "key_data";
    public static String KEY_ADD = "key_add";
    /**
     * 开启
     */
    public static int TYPE_PUSH = 1;
    /**
     * 切换
     */
    public static int TYPE_SWITCH = 2;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_router);
        Class<Fragment> clazz = (Class<Fragment>) getIntent().getSerializableExtra(KEY_TARGET);
        Bundle bundle = getIntent().getBundleExtra(KEY_DATA);
        int type = getIntent().getIntExtra(KEY_TYPE, TYPE_PUSH);
        if(type == TYPE_PUSH) {
            pushFragment(clazz, bundle, getIntent().getBooleanExtra(KEY_ADD, true));
        } else {
            switchFragment(clazz);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Class<Fragment> clazz = (Class<Fragment>) intent.getSerializableExtra(KEY_TARGET);
        Bundle bundle = intent.getBundleExtra(KEY_DATA);
        int type = intent.getIntExtra(KEY_TYPE, TYPE_PUSH);
        if(type == TYPE_PUSH) {
            pushFragment(clazz, bundle, intent.getBooleanExtra(KEY_ADD, true));
        } else {
            switchFragment(clazz);
        }
    }

    @Override
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void pushFragment(Class<? extends Fragment> clazz, Bundle bundle, boolean isAddToBackStack) {
        if(!TextUtils.isEmpty(mTag) && mTag.equals(clazz.getName())) {
           return;
        }
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        Fragment fragment = mFragmentManager.findFragmentByTag(clazz.getName());
        if(fragment == null) {
            fragment = Fragment.instantiate(this, clazz.getName());
            if(bundle != null) {
                fragment.setArguments(bundle);
            }
            transaction.add(R.id.container, fragment, clazz.getName());
            if(isAddToBackStack) {
                transaction.addToBackStack(clazz.getName());
            }
            transaction.commit();
        } else {
            if(bundle != null) {
                if(fragment.getArguments() != null) {
                    fragment.getArguments().clear();
                }
                fragment.setArguments(bundle);
            }
            if(!TextUtils.isEmpty(mTag)) {
                Fragment oldFragment = mFragmentManager.findFragmentByTag(mTag);
                if(oldFragment != null) {
                    transaction.hide(oldFragment);
                }
            }
            transaction.show(fragment).commit();
        }
        mTag = clazz.getName();
    }

    /**
     * 切换到指定的fragment,并弹出中间的fragment
     *
     * @param tagFragment
     */
    @Override
    public void switchFragment(Class<? extends Fragment> tagFragment) {
        if(tagFragment == null || tagFragment.getName().equals(mTag)) {
            return;
        }
        /**
         * 从回退栈弹出tagFragment之上的fragment
         */
        if(mFragmentManager != null && mFragmentManager.getBackStackEntryCount() > 0) {
            mFragmentManager.popBackStackImmediate(tagFragment.getName(), 0);
        }
        if(mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        mTag = tagFragment.getName();
    }

    public void pop() {
        if(mFragmentManager.getBackStackEntryCount() > 1) {
            boolean success = mFragmentManager.popBackStackImmediate();
            if(success) {
                List<Fragment> fragmentList = mFragmentManager.getFragments();
                if(fragmentList != null && fragmentList.size() > 0) {
                    Fragment fragment = fragmentList.get(fragmentList.size() - 1);
                    if(fragment != null) {
                        mTag = fragment.getClass().getName();
                    }
                }
            }
            return;
        }
        finish();
    }

    @Override
    public void onBackPressed() {
        if(mOnBackListener != null) {
            if(mOnBackListener.intercept()) {
                mOnBackListener.onBack();
            }
        } else {
            pop();
        }
    }

    public void setOnBackListener(OnBackListener listener) {
        mOnBackListener = listener;
    }

    /**
     * 监听返回键
     */
    public interface OnBackListener {
        /**
         * 是否需要拦截
         *
         * @return true 拦截 false 不拦截
         */

        boolean intercept();
        void onBack();
    }

}
